package xyz.coolcsm.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.coolcsm.security.entity.*;
import xyz.coolcsm.security.mapper.BlogMapper;
import xyz.coolcsm.security.service.BlogService;
import xyz.coolcsm.security.service.SysUserInfoService;
import xyz.coolcsm.security.service.SysUserService;

import java.util.List;
/**
 * @author 什锦
 * @since 2021-06-1
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserInfoService sysUserInfoService;
    
    @Autowired
    BlogMapper blogMapper;


    @Override
    public void issueBlog(String username, Blog blog) {
        SysUser sysUser = sysUserService.selectByName(username);
        SysUserInfo sysUserInfo = sysUserInfoService.getById(sysUser.getId());
        blog.setAuthorId(sysUserInfo.getUid());
        blog.setAuthorAvatar(sysUserInfo.getAvatar());
        blog.setAuthorName(sysUserInfo.getNickname());
        blogMapper.insert(blog);
    }

    @Override
    public Page<Blog> pageByCid(int page, int limit, int cid) {
        if (page < 1){
            page = 1;
        }
        Page<Blog> pageParam = new Page<>(page, limit);
        QueryWrapper<Blog> wrapper = new QueryWrapper();
        if (cid == 0){
            wrapper.orderByDesc("create_time");
        }
        else if (cid == 1){
            wrapper.orderByDesc("views");
        }else {
            wrapper.orderByDesc("create_time").eq("cid",cid);
        }
        Page<Blog> blogPage = blogMapper.selectPage(pageParam, wrapper);
        return blogPage;
    }

    @Override
    public PageBean<Blog> getBlogList(List<Favorite> strList,int currentPage, int pageSize) {
        PageBean<Blog> pb = new PageBean<Blog>();
        int totalCount = blogMapper.getBlogTotal(strList).size();
        pb.setCurrentPage(currentPage);
        pb.setPageSize(pageSize);
        pb.setTotalCount(totalCount);
        int start = (currentPage-1)*pageSize;
        List<Blog> blogList = blogMapper.getBlogList(strList, start, pageSize);
        pb.setRecords(blogList);
        int totalPage = totalCount % pageSize == 0 ?totalCount / pageSize:(totalCount / pageSize)+1;
        pb.setTotalPage(totalPage);
        return pb;
    }

}
